using System;
using EnvDTE;
using System.IO;
using System.Collections;
using UnitLite.Util;

namespace UnitLite.Util
{
    /// <summary>
    /// This class is used to load project.
    /// </summary>
	public class ProjectLoader
	{
        /// <summary>
        /// Load Project to solution. If existed, load it from local; otherwise, create new one from template. 
        /// </summary>
        /// <param name="solution"></param>
        /// <param name="FullName"></param>
        /// <returns></returns>
		public Project Load(Solution solution, string FullName)
		{
			Project project = null;

			try
			{
                if (solution == null || String.IsNullOrEmpty(FullName))
                {
                    throw new NullReferenceException("Solution or FullName is null");    
                }

				if (File.Exists(FullName))
				{
					project = LoadFromLocal(solution, FullName);
				}
				else
				{
                    project = solution.AddFromTemplate(ProjectSettings.ProjectPath,
                                                       Path.GetDirectoryName(FullName),
                                                       Path.GetFileNameWithoutExtension(FullName),
                                                       false);
				}

			}
			catch (System.Exception e)
			{
				Console.WriteLine(e.Message);
			}

			return project;
		}

        /// <summary>
        /// Load project from local.
        /// </summary>
        /// <param name="solution"></param>
        /// <param name="FullName"></param>
        /// <returns></returns>
		internal Project LoadFromLocal(Solution solution, string FullName)
		{
			string ProjectName = Path.GetFileNameWithoutExtension(FullName);

			Project project = FindProject(solution.Projects, ProjectName);
			if (project == null)
			{
				project = solution.AddFromFile(FullName, false);
				project.Name = ProjectName;
			}

			return project;
		}

        /// <summary>
        /// Find the target project from projects by name.
        /// </summary>
        /// <param name="projects"></param>
        /// <param name="Name"></param>
        /// <returns></returns>
		public Project FindProject(Projects projects, string Name)
		{
            if (projects == null || projects.Count == 0)
            {
                return null;
            }

            if (String.IsNullOrEmpty(Name))
            {
                return null;
            }

			Project project = null;

			IEnumerator it = projects.GetEnumerator();
			
            while (it.MoveNext())
			{
				Project tmp = it.Current as Project;
				if (tmp.Name == Name)
				{
					project = tmp;
					break;
				}
			}
			return project;
		}
	}
}